package com.flamingskys.learn.rag.es.config;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import java.net.URI;
import java.util.List;
import java.util.stream.Collectors;

@Configuration
public class ElasticsearchConfig {

    private final ElasticsearchProperties elasticsearchProperties;

    @Autowired
    public ElasticsearchConfig(ElasticsearchProperties elasticsearchProperties) {
        this.elasticsearchProperties = elasticsearchProperties;
    }

    @Bean
    public RestHighLevelClient elasticsearchClient() {
        // 将 URI 转换为 host:port 格式
        List<String> hostsAndPorts = elasticsearchProperties.getUris().stream()
                .map(uri -> {
                    URI parsed = URI.create(uri);
                    return parsed.getHost() + ":" + parsed.getPort();
                })
                .collect(Collectors.toList());

        ClientConfiguration clientConfiguration = ClientConfiguration.builder()
                .connectedTo(hostsAndPorts.toArray(new String[0]))
//                .withBasicAuth(elasticsearchProperties.getUsername(), elasticsearchProperties.getPassword())
                .withConnectTimeout(elasticsearchProperties.getConnectionTimeout())
                .withSocketTimeout(elasticsearchProperties.getSocketTimeout())
                .build();

        return RestClients.create(clientConfiguration).rest();
    }

    @Bean
    public ElasticsearchOperations elasticsearchTemplate() {
        return new ElasticsearchRestTemplate(elasticsearchClient());
    }
}